# The AtomReq module provides some helpers methods which encapsulates Atom requests.

require 'net/http'
require 'atom/collection'
require 'atom/entry'

module PNEngine
  module AtomReq
    def self.get!(url)
      url = URI.parse(url) if url.is_a? String
      res = Net::HTTP.start(url.host, url.port) do |http|
        req = Net::HTTP::Get.new(url.path)
        req["ACCEPT"] = "application/atom+xml"
        http.request(req)
      end
    end
    
    def self.head!(url)
      url = URI.parse(url) if url.is_a? String
      res = Net::HTTP.start(url.host, url.port) do |http|
        req = Net::HTTP::Head.new(url.path)
        req["ACCEPT"] = "application/atom+xml"
        http.request(req)
      end
    end
    
    def self.get_entry!(url)
      begin
        Atom::Entry.parse(get!(url).body, url)
      rescue Atom::ParseError
        nil
      end
    end
    
    def self.get_feed!(url)
      begin
        Atom::Collection.parse(get!(url).body, url)
      rescue Atom::ParseError
        nil
      end
    end

    def self.put!(url, body = nil, &block)
      url = URI.parse(url) if url.is_a? String
      res = Net::HTTP.start(url.host, url.port) do |http|
        req = Net::HTTP::Put.new(url.path)
        req["ACCEPT"] = "application/atom+xml"
        req.body = body.to_s
        yield req if block_given?
        http.request(req)
      end
    end

    def self.post!(url, body = nil, &block)
      url = URI.parse(url) if url.is_a? String
      res = Net::HTTP.start(url.host, url.port) do |http|
        req = Net::HTTP::Post.new(url.path)
        req["ACCEPT"] = "application/atom+xml"
        req.body = body.to_s
        yield req if block_given?
        http.request(req)
      end
    end
    
    def self.post_entry!(url, body)
      res = self.post!(url, body.to_s)
      if res.kind_of? Net::HTTPSuccess
        get_entry!(res["Location"])
      else
        nil
      end
    end
    
    def self.delete!(url)
      url = URI.parse(url) if url.is_a? String
      res = Net::HTTP.start(url.host, url.port) do |http|
        req = Net::HTTP::Delete.new(url.path)
        req["ACCEPT"] = "application/atom+xml"
        http.request(req)
      end
    end
  end
end